import java.util.*;

public class Demo {
}
class Solution {
    public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
        List<Boolean> ans = new ArrayList<>();
        List<List<Integer>> map = new ArrayList<>();
        for(int i=0; i<numCourses; i++){
            map.add(new ArrayList<>());
        }
        for(int[] x : prerequisites){
            map.get(x[0]).add(x[1]);//课程有哪些后置课程
        }
        for(int[] x : queries){
            int pre = x[0], cur = x[1];
            if(isValid(pre,cur,map)){
                ans.add(true);
            }else{
                ans.add(false);
            }
        }
        return ans;
    }
    boolean isValid(int pre, int cur, List<List<Integer>> map){
        Queue<Integer> q = new LinkedList<>();
        q.offer(pre);
        Set<Integer> set = new HashSet<>();
        set.add(pre);
        while(!q.isEmpty()){
            int tmp = q.poll();
            for(int x : map.get(tmp)){
                if(x == cur) return true;
                if(!set.contains(x)){
                    q.offer(x);
                    set.add(x);
                }
            }
        }
        return false;
    }
}
